package bosVM2.FaultHandling;

public class AnCodeFaultHandler {
	
	private int _ANCODE = 3;
	private int _ANCODED = new Integer(_ANCODE);

	private static AnCodeFaultHandler instance = new AnCodeFaultHandler();
	private AnCodeFaultHandler() {}
	public static AnCodeFaultHandler getAnFaultHAndler() { return instance; }
	
	private int ANCODE()
	{
		//Not using the valid method to avoid an endless loop
		if(_ANCODED % _ANCODE != 0)
		{
			refreshCoding();
			return _ANCODE;
		} else return _ANCODED;
	}
	
	public int enCode(int value) {
		return value*ANCODE();
	}
	
	public int deCode(int value) {
		return value/ANCODE();
	}
	
	public boolean valid(int i) {
		if(i % ANCODE() != 0)
		{ return false; }
		else return true;
	}
	
	public int handleValueFault(int orig, int coded) {
		if(!valid(coded)) {
			return orig;
		}
		else {
			return deCode(coded);
		}
	}
	//refresh the coding:
	//This will be called under assumption that the coded ancode is corrupt and that the ancode is intact.
	//No assumptions are made about the ancode copy, which doesnt even exist anymore
	private void refreshCoding() {
		_ANCODED = enCode(_ANCODE);
	}

}
